package org.duiduo.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.duiduo.api.enums.DeviceTypeEnum;
import org.duiduo.api.req.LoginReq;
import org.duiduo.entity.LoginUser;
import org.duiduo.mapper.UserMapper;
import org.duiduo.pojo.User;
import org.duiduo.service.AuthService;
import org.duiduo.util.ContextUtil;
import org.duiduo.util.SecurityUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录注册业务
 *
 * @author liangze
 * @date 2025/9/29 16:05
 */
@Slf4j
@Component
public class AuthServiceImpl implements AuthService {

    @Inject
    private UserMapper userMapper;

    @Override
    public Map<String, Object> login(LoginReq req) {
        String username = req.getUsername();
        String password = req.getPassword();
        if (!StrUtil.isAllNotEmpty(username, password)) {
            throw new IllegalArgumentException("账号/密码必须填写");
        }
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq("username", username));
        Assert.notNull(user, "当前用户名不存在");
        Assert.equals(user.getPassword(), password, "密码错误");

        LoginUser loginUser = new LoginUser();
        loginUser.setId(user.getId());
        loginUser.setUsername(user.getUsername());
        loginUser.setDeviceType(DeviceTypeEnum.PC.getCode());
        loginUser.setIpaddr(ContextUtil.getIpAddr());
        SecurityUtil.login(loginUser, DeviceTypeEnum.PC.getCode());

        Map<String, Object> map = new HashMap<>();
        map.put("access_token", loginUser.getToken());
        map.put("expires_in", loginUser.getExpireTime());
        return map;
    }

}
